package com.jysz.certificate.service.pm;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.pm.AssignUserDao;
import com.jysz.certificate.persistence.model.pm.AssignUser;
import com.jysz.certificate.persistence.model.pm.PerformanceAssign;
import com.jysz.certificate.persistence.model.pm.PmUserList;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.system.UserService;
import com.jysz.webcore.ssh.service.EntityService;

/**
 * @author <a href="mailto:javaengine@outlook.com">Kaca Rich</a>
 *
 */
@Service
public class AssignUserService extends EntityService<AssignUser, Long, AssignUserDao>{

	@Resource
	private AssignUserDao assignUserDao;
	@Resource
	private UserService userService;
	@Resource
	private PmUserListService pmUserListService;
	@Resource
	private PAShopMonthDetailService paShopMonthDetailService;
	@Override
	public AssignUserDao getEntityDao() {
		return assignUserDao;
	}

	public void destoryAndUpdateAmount(AssignUser assignUser) {
		double newAmount = assignUser.getPaShopMonthDetail().getTotalAmount() - assignUser.getAmount();
		
		paShopMonthDetailService.updateUpTotalAmount(assignUser.getPaShopMonthDetail(), newAmount);
		
		PmUserList pmUserList = assignUser.getPaShopMonthDetail().getPmUserList();
		List<User> users = pmUserList.getUsers();
		if(users != null && users.contains(assignUser.getUser())){
			users.remove(assignUser.getUser());
			pmUserListService.save(pmUserList);
		}
		
		this.destory(assignUser);
	}

	/**
	 * 自己创建一个新的分配对象。
	 * @param assignUser
	 */
	public void saveCreateNewAssignUser(AssignUser assignUser) {
		User user = userService.find(assignUser.getUser().getId());
		assignUser.setUser(user);
		PmUserList pmUserList = assignUser.getPaShopMonthDetail().getPmUserList();
		List<User> users = pmUserList.getUsers();
		if(users == null){
			users = new ArrayList<User>();
		}
		
		if(!users.contains(user)){
			users.add(user);
			pmUserList.setUsers(users);
			pmUserListService.save(pmUserList);
		}
		
		paShopMonthDetailService.updateUpTotalAmount(assignUser.getPaShopMonthDetail(), assignUser.getPaShopMonthDetail().getTotalAmount() + assignUser.getAmount());
		this.save(assignUser);
	}

	@SuppressWarnings("unchecked")
	public List<AssignUser> findByPerformanceAssign(PerformanceAssign entity) {
		Criteria criteria = this.getEntityDao().createCriteria();
		criteria.createCriteria("paShopMonthDetail").createCriteria("performanceAssignShopDetail").add(Restrictions.eq("performanceAssign", entity));
		
		return criteria.list();
	}
	
}
